import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../components/app_conifg.dart';
import '../../goods/binding/goods_detail_binding.dart';
import '../../goods/view/goods_detail_page.dart';

///我的红包控制器
class RedPackController extends BaseController with GetSingleTickerProviderStateMixin {
  late TabController tabController;

  RefreshController freshCtr = RefreshController(initialRefresh: false);

  TextEditingController codetxtController = TextEditingController();

  var dataList = [].obs;
  var page = 1.obs;

  var marketPage = 1.obs;
  var qccrep = 1.obs;

  var goodsList = [].obs;
  var qccrepGoodsList = [].obs;

  int status = 0;

  bool hasNextPage = true;

  bool listNextPage = true;

  ///订单信息
  var orderInfo = {}.obs;

  ///ture：购券中心
  var isCouponsCenter = false.obs;

  @override
  void onInit() {
    super.onInit();
    getRedpackList();
    queryCanClaimedRedPacketList();
    tabController = TabController(length: 3, vsync: this);
    tabController.addListener(() {
      if (tabController.indexIsChanging) {
        status = tabController.index;
        dataList.value = [];
        page.value = 1;
        getRedpackList();
      }
    });
  }

  //获取我的红包
  Future getRedpackList() async {
    Tools.showLoading();
    logger.d('获取我的红包');
    Network.getMyRedPacketList(status, page.value, 10).then((value) {
      //print(value['list']);
      hasNextPage = value['hasNextPage'];
      if (page.value == 1) {
        dataList.value = value['list'];
      } else {
        dataList.addAll(value['list']);
      }
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  ///兑换
  Future exchange() async {
    if (codetxtController.text == '') {
      Tools.showToast("请先输入兑换码");
    } else {
      Tools.showLoading();
      Network.exchangeRedpack(codetxtController.text).then((value) {
        if (value == true) {
          Tools.showToast("兑换成功");
          Tools.hideLoading();
        }
      }).catchError((error) {
        Tools.hideLoading();
      });
    }
  }

  //红包退款
  Future refund(String id) async {
    Tools.showLoading();
    Network.redpackRefund(id).then((value) {
      //print(value);
      if (value) {
        Tools.showToast("退款申请已提交到后台");
        getRedpackList();
      }
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
  }

  @override
  void onPageRefresh() async {
    super.onPageRefresh();
    page.value = 1;
    await getRedpackList();
    baseRefreshCtr.refreshCompleted(resetFooterState: true);
  }

  @override
  void onPageLoading() async {
    super.onPageLoading();
    if (hasNextPage) {
      page.value += 1;
      await getRedpackList();
      baseRefreshCtr.loadComplete();
    }
  }

  //前往红包市场
  void toMarket() {
    Get.toNamed(Routes.redpackMarket);
  }

  ///订单详情
  void orderDetail(Map item) {
    final id = item['commodityId'];
    Get.to(
      () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
      routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
      arguments: {"id": id}, // 传递其它参数
      binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
    );
  }

  ///加减数量
  void setBuyNum(int num) {
    orderInfo['buyNum'] = num;
    orderInfo['totalPrice'] = (num * orderInfo['price']).toStringAsFixed(2);
    update();
  }

  //购券中心
  Future getRedpackGoodsList() async {
    isCouponsCenter.value = true;
    Tools.showLoading();
    Network.getGoodsList({"sid": AppData.sid, "commodityForm": 2, "pageNum": marketPage.value, "pageSize": 10}).then((value) {
      // print(value['list']);
      listNextPage = value['hasNextPage'];
      if (marketPage > 1) {
        goodsList.addAll(value['list']);
      } else {
        goodsList.value = value['list'];
      }
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
    update();
  }

  //领券中心
  Future queryCanClaimedRedPacketList() async {
    isCouponsCenter.value = false;
    Tools.showLoading();
    Network.queryCanClaimedRedPacketList({"sid": AppData.sid, "pageNum": qccrep.value, "pageSize": 10}).then((value) {
      listNextPage = value['hasNextPage'];
      if (qccrep > 1) {
        qccrepGoodsList.addAll(value['list']);
      } else {
        qccrepGoodsList.value = value['list'];
      }
      Tools.hideLoading();
    }).catchError((error) {
      Tools.hideLoading();
    });
    update();
  }

  void submit() {
    if (orderInfo.isEmpty) {
      Tools.showToast("请先选择商品");
    } else {
      Tools.showLoading();
      //这里执行下单逻辑,下单成功才跳结算
      Map<String, dynamic> params = {};
      params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
      params['shippingType'] = 0;
      params['goodsList'] = [
        {"buyNum": orderInfo['buyNum'], "goodsId": orderInfo['commodityId'], "specNum": orderInfo['specNum']},
      ];
      params['sid'] = AppData.sid;
      params['type'] = 6;

      //  params['dto']={params['client'] = "android",params['shippingType'] = 0,params['goodsList'] = [
      //   {"buyNum":orderInfo['buyNum'],"goodsId":orderInfo['commodityId'],"specNum":orderInfo['specNum']},
      // ],params['sid'] = AppData.sid,params['type'] = 6,};

      Network.prePlaceOrder(params).then((value) {
        Tools.hideLoading();

        Network.placeOrder(params).then((value) {
          //跳转到结算页面
          Get.toNamed('${Routes.cashier}/?sn=${value['paySn']}&price=${value['priceOrder']}');
        });
      }).catchError((onError) {
        //print(onError);
        Tools.hideLoading();
      });
    }
  }

  void onMarketPageRefresh() async {
    super.onPageRefresh();
    if (isCouponsCenter.value) {
      marketPage.value = 1;
      await getRedpackGoodsList();
    } else {
      qccrep.value = 1;
      await queryCanClaimedRedPacketList();
    }

    // 完成下拉刷新，并重置 footer 状态
    freshCtr.refreshCompleted(resetFooterState: !listNextPage);
    // 根据是否有更多数据来设置 footer 的状态
    if (listNextPage) {
      freshCtr.resetNoData(); // 重置为上拉加载状态
    } else {
      freshCtr.loadNoData(); // 显示 "没有更多数据"
    }
  }

  void onMarketPageLoading() async {
    super.onPageLoading();
    if (isCouponsCenter.value) {
      if (listNextPage) {
        marketPage.value += 1;
        await getRedpackGoodsList();
      }
    } else {
      if (listNextPage) {
        qccrep.value += 1;
        await queryCanClaimedRedPacketList();
      }
    }
    if (listNextPage) {
      freshCtr.loadComplete();
    } else {
      freshCtr.loadNoData();
    }
  }

  ///领取红包
  void receiveRedPack(String redPacketId) async {
    await Network.receiveRedPack(redPacketId);
    Tools.showToast('领取成功');
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }
}
